import {request} from "../request";
import {showModal} from "../ui";

// 生成二维码
function makeQrCode(url) {
	return request.get(url, {}, {
		showLoading: false,
		tipsSuccessMsg: false,
	}).then(function(res) {
		const path = res.data;

		return new Promise(function(resolve, reject) {
			const img = new Image();
			img.src = path;
			img.onload = resolve;
			img.onerror = reject;
		});
	});
}

// 检测登录工厂函数
function checkLoginFactory(url, makeTime, timeout = 300) {
	// 检测定时器ID
	let poolTimerId = 0;
	// 是否终止检测
	let isStop = false;

	// 开始检测
	function start(success, fail) {
		request.post(url, {}, {
			showLoading: false,
			tipsSuccessMsg: false,
		}).then(function(res) {
			if (res.data.status === 1) {
				poolTimerId = 0;
				success();
			} else {
				const currentTime = Math.floor(new Date().getTime() / 1000);
				if ((makeTime + timeout) > currentTime) {
					setTimeout(function() {
						start(success, fail);
					}, 1000);
				} else {
					poolTimerId = 0;
					fail();
				}
			}
		}, function() {
			poolTimerId = 0;
			fail();
		});
	}

	// 终止执行
	function stop() {
		isStop = true;
		clearTimeout(poolTimerId);
	}

	return {
		start,
		stop
	};
}

export default function(options) {
	// if (!options.makeUrl) {
	// 	return Promise.reject("生成二维码地址不能为空！");
	// }
	//
	// if (!options.checkUrl) {
	// 	return Promise.reject("检测是否已登录地址不能为空！");
	// }

	const TPL = `
<div style="font-weight: bold;font-size: 20px;text-align: center;line-height: 2;margin-top: 15px">${options.title || "登录二维码"}</div>
<img src="" alt="" style="border-radius: 5px;border:1px solid #eee;width: 200px;height: 200px;display: block;margin: 15px auto;padding: 15px;"/>
<p style="font-size: 12px;color: gray;text-align: center">${options.description || "手机扫一扫快捷登录"}</p>
`;
	return makeQrCode(options.makeUrl).then(function(img) {
		new Promise(function(resolve) {
			showModal({
				area: ['320px', '400px'],
				content: TPL,
				btn: false,
				created: function(winCtx) {
					// const container = winCtx.popup.find('.layui-layer-content');
					// makeQrCode(function(img) {
					// 	const path = img.src;
					// 	poolCheckLogin(resolve, function() {
					// 		xin.close(winCtx.index);
					// 		xin.showModal({
					// 			content: '登录二维码已失效，请重新打开~',
					// 			showCancel: false
					// 		});
					// 	});
					// });
				}
			});
		});
	});
}
